<script lang="ts" setup>
import Item from './components/Item.vue'
import { updateDetails } from '@/api/user'
import type { IUser } from '@/typings/interface'
import { baseUrl } from '@/utils/request'
import type { IDialog } from '@/typings/components'

interface IItem {
  name: string
  key: keyof IUser
}
// 输入框弹窗初始定义变量
const inputDialog = $ref<IDialog>()
// 每项信息初始变量
let currentItem = $ref<IItem>()
const { details, token } = $(useUser())
const { base, success } = useToast()

// 展示用户的默认信息
let copyDetails = $ref(JSON.parse(JSON.stringify(details)))

// 重置为默认信息
function resetCopyDetails() {
  copyDetails = JSON.parse(JSON.stringify(details))
}

// 每项信息输入框点击按钮
function onItemClick(info: IItem) {
  inputDialog?.open()
  currentItem = info
}

// 每项输入框的确认按钮
function onConfirm(value: string) {
  if (currentItem)
    copyDetails[currentItem.key] = value
  else
    base('出现错误，请重试')
  inputDialog?.close()
}

// 性别默认变量
const sexChecked = $ref(!!details?.sex)

// 保存按钮
async function save() {
  // 修改接口请求
  const res = await updateDetails({
    id: copyDetails.id,
    username: copyDetails.username,
    slogan: copyDetails.slogan,
    sex: sexChecked ? 1 : 0,
    city: copyDetails.city,
  })
  if (res.code === 0)
    success(res.msg || '保存成功')
  else
    base(res.msg || '保存失败')
  // 更新用户信息
  await useUser().syncUserInfo()
  resetCopyDetails()
}

// 更新头像
async function onAvatarClick() {
  // 从本地选择图片
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      base('上传中……')
      // 上传图片
      uni.uploadFile({
        url: `${baseUrl}/user/v1/update_img`,
        fileType: 'image',
        name: 'headImg',
        header: { Authorization: token },
        filePath: res.tempFilePaths[0],
        success: async ({ data }) => {
          const res = JSON.parse(data) as { code: number; msg: string }
          if (res.code === 0)
            success(res.msg || '上传成功')
          else
            base(res.msg || '上传失败，请重试')
          await useUser().syncUserInfo()
          resetCopyDetails()
        },
        fail: () => {
          base('上传失败，请重试')
        }
      })
    }
  })
}
</script>

<template>
  <view>
    <view class="list">
      <Item title="头像">
        <template #extra>
          <image :src="copyDetails?.head_img" class="w-80 h-80" @click="onAvatarClick" />
        </template>
      </Item>

      <view @click="onItemClick({ name: '昵称', key: 'username' })">
        <Item title="昵称">
          <template #extra>
            {{ copyDetails?.username || '昵称' }}
          </template>
        </Item>
      </view>

      <Item title="性别">
        <template #extra>
          <radio-group text-40 @change="sexChecked = !sexChecked">
            <radio value="男" :checked="sexChecked" color="#aaaaaa" style="transform: scale(0.6)">
              男
            </radio>
            <radio value="女" :checked="!sexChecked" ml--1 color="#aaaaaa" style="transform: scale(0.6)">
              女
            </radio>
          </radio-group>
        </template>
      </Item>

      <view @click="onItemClick({ name: '城市', key: 'city' })">
        <Item title="城市">
          <template #extra>
            {{ copyDetails?.city || '未设置' }}
          </template>
        </Item>
      </view>

      <view @click="onItemClick({ name: '个性签名', key: 'slogan' })">
        <Item title="个性签名" is-end>
          <template #extra>
            {{ copyDetails?.slogan || '未设置个性签名' }}
          </template>
        </Item>
      </view>
    </view>

    <view @click="save">
      <button class="setting_button" plain hover-class="setting_button_hover">
        保存
      </button>
    </view>

    <!-- 输入框编辑弹窗 -->
    <view>
      <uni-popup ref="inputDialog" type="dialog">
        <uni-popup-dialog mode="input" :title="`修改${currentItem?.name}`"
          :value="currentItem ? copyDetails[currentItem.key] : ''" :placeholder="`请输入要修改的${currentItem?.name}`"
          @confirm="onConfirm" />
      </uni-popup>
    </view>
  </view>
</template>
<style lang="scss" scoped>
.setting_button {
  margin: 0;
  padding: 0;
  width: 100%;
  padding: 5rpx 0;
  color: #f38e48;
  font-size: 30rpx;
  margin-top: 40rpx;
  border: none !important;
  box-shadow: 0 0 20rpx 0 rgba(215, 215, 215, 0.35);

  &_hover {
    color: white;
    background-color: #f38e48;
  }
}

.list {
  width: 100%;
  color: #333333;
  margin-top: 30rpx;
  background-color: white;
  box-shadow: 0 0 20rpx 0 rgba(215, 215, 215, 0.35);
}
</style>